import Vue from 'vue'
import { useCoordPicker } from '@/utils/init.js'

const state = {
  sidebar: {
    opened:
      localStorage.getItem('sidebarStatus') &&
      !window.__POWERED_BY_QIANKUN__ &&
      window.top === window
        ? !!+localStorage.getItem('sidebarStatus')
        : true,
    withoutAnimation: false,
    showBar: true,
    showLabel: true
  },
  device: 'desktop',
  systemInfo: {
    name: '一码游', // 平台名称
    logo: '', // logo
    mapCity: '' // 高德地图key
  }
}

const mutations = {
  TOGGLE_SIDEBAR: state => {
    state.sidebar.opened = !state.sidebar.opened
    state.sidebar.withoutAnimation = false
    if (state.sidebar.opened) {
      localStorage.setItem('sidebarStatus', 1)
    } else {
      localStorage.setItem('sidebarStatus', 0)
    }
  },
  TOGGLE_SHOWBAR: (state, isShow) => {
    state.sidebar.showBar = isShow
  },
  OPEN_SIDEBAR: state => {
    localStorage.setItem('sidebarStatus', 1)
    state.sidebar.opened = true
  },
  CLOSE_SIDEBAR: (state, withoutAnimation) => {
    localStorage.setItem('sidebarStatus', 0)
    state.sidebar.opened = false
    state.sidebar.withoutAnimation = withoutAnimation
  },
  TOGGLE_DEVICE: (state, device) => {
    state.device = device
  },
  SYSTEM_INFO_CHANGE: (state, info) => {
    // 处理初始化数据
    info.forEach(item => {
      if (item.propValue) {
        state.systemInfo[item.propName] = item.propValue
      }
      if (item.propName == 'logo') {
        document.querySelector('#title-icon').href = item.propValue
      }
      if (item.propName == 'mapCity') {
        useCoordPicker(item.propValue) // 注册坐标拾取组件
      }
      if (item.propName == 'name') {
        document.title = item.propValue
      }
    })
  }
}

const actions = {
  // 获取平台基础配置
  getSystemInfo ({ commit }) {
    Vue.prototype
      .$POST('sot-admin-api/sys/auth/queryBasicInfoConfig')
      .then(res => {
        if (res.errorCode == '00000') {
          commit('SYSTEM_INFO_CHANGE', res.data)
        }
      })
  },
  toggleSideBar ({ commit }) {
    commit('TOGGLE_SIDEBAR')
  },
  openSideBar ({ commit }) {
    commit('OPEN_SIDEBAR')
  },
  closeSideBar ({ commit }, { withoutAnimation }) {
    commit('CLOSE_SIDEBAR', withoutAnimation)
  },
  toggleDevice ({ commit }, device) {
    commit('TOGGLE_DEVICE', device)
  },
  toggleShowBar ({ commit }, isShow) {
    commit('TOGGLE_SHOWBAR', isShow)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
